package com.gmstu.springframework.mvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author John.zhang
 * @version Id: GpView, v 1.0 2020/8/24 15:21 ZhiYong Exp $
 */
public class GpView {

    private static Pattern PATTERN = Pattern.compile("￥\\{[^}]+}", Pattern.CASE_INSENSITIVE);

    private File viewFile;

    public GpView(File viewFile) {
        this.viewFile = viewFile;
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuilder builder = new StringBuilder();
        RandomAccessFile r = new RandomAccessFile(this.viewFile, "r");

        String line;
        while (null != (line = r.readLine())) {
            line = new String(line.getBytes("ISO-8859-1"), "utf-8");
            Matcher matcher = PATTERN.matcher(line);
            while (matcher.find()) {
                String paramName = matcher.group().replaceAll("￥\\{|}", "");
                Object paramValue = model.get(paramName);
                if (null == paramValue) {
                    continue;
                }
                line = matcher.replaceFirst(paramValue.toString());
                matcher = PATTERN.matcher(line);
            }
            builder.append(line);
        }
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(builder.toString());
    }
}
